package com.springboot.aspect;

import com.springboot.annotation.Log;
import com.springboot.dao.SysLogDao;
import com.springboot.pojo.SysLog;
import com.springboot.util.HttpContextUtils;
import com.springboot.util.IPUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author peter
 * @title: LogAspect
 * @projectName springAll-peter
 * @description: TODO
 * @date 19-5-6上午9:48
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysLogDao sysLogDao;

    @Pointcut("@annotation(com.springboot.annotation.Log)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public void around(ProceedingJoinPoint point) {
        long beginTime = System.currentTimeMillis();

        try {
            //执行方法
            point.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        //执行时长（毫秒）
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveLog(point, time);


    }

    private void saveLog(ProceedingJoinPoint point, long time) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        Log annotation = method.getAnnotation(Log.class);

        if (annotation != null) {
            //注解上的描述
            sysLog.setOperation(annotation.value());
        }
        //请求的方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();

        sysLog.setMethod(className + "." + methodName + "()");

        //请求的方法参数值
        Object[] args = point.getArgs();

        //请求方法的参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);

        if (args != null && paramNames != null) {
            String params = "";

            for (int i = 0; i < args.length; i++) {
                params += " " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();

        //设置ip地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        sysLog.setUsername("peter.zhang");
        sysLog.setTime((int) time);

        Date date = new Date();

        sysLog.setCreateTime(date);

        //保存系统日志
        sysLogDao.saveSysLog(sysLog);

    }


}
